<?php
class Simpple_Model_MysqlProxy extends Simpple_Model_Mysql {
	/**
	 * @var Simpple_Model_Mysql
	 */
	private $master;
	/**
	 * @var Simpple_Model_Mysql
	 */
	private $slave;
	
	private $useSlave = false;
	
	public function __construct($resource = null) {
		if (!$resource) {
			$this->master = $resource;
			$this->resource = $resource;
		}
	}
	/**
	 * 设置主服务器
	 *
	 * @param array $options
	 */
	public function setMaster($options) {
		$this->master = Simpple_Model_Mysql::factory($options);
		$this->resource = $this->master;
	}
	/**
	 * 设置从服务器
	 *
	 * @param array $options
	 */
	public function setSlave($options) {
		$this->slave = Simpple_Model_Mysql::factory($options);
		$this->useSlave = true;
	}
	
	/**
	 * 覆写执行方法
	 *
	 * @param string $sql
	 */
	public function execute($sql) {
		if ($this->useSlave) {
			$tmpSql = trim($sql);
			$cmd = substr($tmpSql, 0, strpos($tmpSql, ' '));
			if (in_array($cmd, array('select','show','desc'))) {
				$this->resource = $this->slave;
			} else {
				$this->resource = $this->master;
			}
		}
		return parent::execute($sql);
	}
	
	public function close() {
		if ($this->master) {
			mysql_close($this->master);
		}
		if ($this->slave) {
			mysql_close($this->slave);
		}
	}
}